package com.my.hotel.controller;

import com.github.pagehelper.PageInfo;
import com.my.hotel.entity.Menu;
import com.my.hotel.entity.Role;
import com.my.hotel.entity.RoleMenu;
import com.my.hotel.entity.UserRole;
import com.my.hotel.service.MenuService;
import com.my.hotel.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    //分页查询
    @RequestMapping("/rolePage")
    public String getPage(Model model, Integer pageNo){
        if(pageNo==null){
            pageNo=1;
        }
        PageInfo<Role> page = roleService.getPage(pageNo);
        model.addAttribute("page",page);
        return "rolePage";
    }

    //角色预添加
    @RequestMapping("/addPreRole")
    public String addPreRole(){
        return "roleAdd";
    }
    //角色添加
    @RequestMapping("/addRole")
    public String addRole(Role role,Model model){
        roleService.addRole(role);
        return getPage(model);
    }

    //角色删除
    @RequestMapping("/delRole")
    public String delRole(int id,Model model){
        roleService.delRole(id);
        return getPage(model);
    }

    //角色预修改
    @RequestMapping("/updPreRole")
    public String updPreRole(int id,Model model){
        Role role = roleService.getRoleById(id);
        model.addAttribute("role",role);
        return "roleUpdate";
    }

    //角色修改
    @RequestMapping("/updRole")
    public String updRole(Role role,Model model){
        roleService.updRole(role);
        return getPage(model);
    }

    //跳转到分配页面
    @RequestMapping("/toDistMenu")
    public String toDistMenu(int roleId,Model model){
        //查询已分配的菜单
        List<Menu> distMenu = menuService.getDistMenu(roleId);
        //查询未分配的菜单
        List<Menu> unDistMenu = menuService.getUnDistMenu(roleId);
        model.addAttribute("distMenu",distMenu);
        model.addAttribute("unDistMenu",unDistMenu);
        model.addAttribute("roleId",roleId);
        //ctrl +x
        return "distMenu";
    }

    //添加角色关联菜单的数据
    @RequestMapping("/addRoleMenu")
    public String addRoleMenu(int roleId,int[] menuId){
        ArrayList<RoleMenu> list = new ArrayList<RoleMenu>();
        for (int mid : menuId) {
            RoleMenu rm = new RoleMenu();
            rm.setRoleId(roleId);
            rm.setMenuId(mid);
            list.add(rm);
        }
        roleService.addRoleMenu(list);
//        userService.addUserRole(list);
        return "success";
    }

    //重载一下
    public String getPage(Model model){
        return getPage(model,1);
    }
}
